import {Component, OnInit, TemplateRef} from '@angular/core';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {FetchService} from '../../../core/net/fetch.service';
import {NzMessageService, NzTreeNode} from 'ng-zorro-antd';
import {BehaviorSubject, Subject} from "rxjs";
import {MenuItemModel} from "../../../core/auth/auth.service";
import {takeUntil} from "rxjs/operators";
import {UtilService} from "../../../core/util/util.service";
import {UploadFile} from 'ng-zorro-antd/upload';
import {UploadChangeParam} from 'ng-zorro-antd/upload';
import {NzModalRef, NzModalService} from "ng-zorro-antd/modal";


@Component({
  selector: 'app-materials',
  templateUrl: './materials.component.html',
  styleUrls: ['./materials.component.scss']
})
export class MaterialsComponent implements OnInit {
  uploadUrl = `${(window as any).environment.apiBaseUrl}comm/file/upload`;
  rightTableData;

  searchValue = "";
  activedNode: NzTreeNode;
  selectedItem: any;
  expandKeys;
  defaultKeys;

  searchForm: FormGroup;

  dataSource;
  menuList: Array<MenuItemModel>;

  treeDataChange = new BehaviorSubject<MenuItemModel[]>([]);
  unsubscribe: Subject<void> = new Subject<void>();
  modalTitle: string = '';
  modalShow: boolean = false;
  nzBodyStyle: any = {
    padding: '16px 20px 0'
  };
  folderForm: FormGroup;
  fileList: UploadFile[] = [];
  fileModalTitle = '文件上传';
  fileModalShow = false;
  uploadFileId = '';

  total: number;
  pageNum = 1;
  pageSize = 15;
  loading = false;

  // 文件预览
  tplModal: NzModalRef;
  fileSrc = '';
  fileType = '';
  fileId = '';
  fileTypeList = ['pdf', 'png', 'jpg'];
  constructor(private fb: FormBuilder,
              private utilService: UtilService,
              private fetchService: FetchService,
              private modal: NzModalService,
              private message: NzMessageService) {
    this.searchForm = this.fb.group({
      fileName: ['']
    });

    this.folderForm = this.fb.group({
      id: [''],
      name: ['', Validators.required],
      pid: ['', Validators.required]
    });

  }

  ngOnInit(): void {
    this.treeDataChange.pipe(takeUntil(this.unsubscribe)).subscribe(data => {
      this.getTreeData(data);
      this.dataSource = data;
      if (data.length > 0) {
        this.expandKeys = [this.dataSource[0].key];
        this.defaultKeys = [this.dataSource[0].children[0].key];
        this.checkDetail(this.dataSource[0]);
      }

    });

    this.fetchMenuList();
  }

  private formatToCascadeData(data, rootId): any {
    const formatArr = data.map(item => {
      return {...item, ...{children: []}};
    });
    return this.listToTreeWithLevel(formatArr, null, 0, rootId);
  }

  private listToTreeWithLevel(list, parent, level, rootId?): Array<any> {
    const out = [];
    for (const node of list) {
      if (node.pid === parent) {
        node.level = level;
        const children = this.listToTreeWithLevel(list, node.id, level + 1, rootId);
        if (children.length) {
          node.children = children;
        }
        out.push(node);
      }
    }
    return out;
  }

  private fetchMenuList(force?: boolean): void {
    if (force || !this.menuList) {
      this.fetchService
        .post<any>("archives/wrsDoc/list", {pageSize: 500})
        .pipe(takeUntil(this.unsubscribe))
        .subscribe(res => {
          res.list.unshift({id: 0, name: "类目", pid: null});
          this.menuList = this.formatToCascadeData(res.list, 0);
          this.treeDataChange.next(this.menuList);

        });
    }
  }

  getTreeData(data) {
    data.map(item => {
      item.title = item.name;
      item.key = item.id;
      if (item.children && item.children.length) {
        this.getTreeData(item.children);
      } else {
        item.isLeaf = true;
      }
    });
  }

  getGridData(reset: boolean = false): void {
    if (reset) {
      this.pageNum = 1;
    }
    const param = {
      docId: this.selectedItem.id || '',
      fileName: this.searchForm.value.fileName,
      pageNum: this.pageNum,
      pageSize: this.pageSize
    };
    this.fetchService.post<any>('archives/wrsDocFile/list', param).subscribe(res => {
      this.rightTableData = res.list;
      this.total = res.total;
    });
  }

  onConfirm(): void {
    if (!this.folderForm.valid) {
      this.message.warning('信息填写有误');
      return;
    }
    const data = this.folderForm.value;
    if (data.id) {
      this.fetchService.post('archives/wrsDoc/edit', data).subscribe(res => {
        this.modalShow = false;
        this.fetchMenuList(true);
      });
    } else {
      this.fetchService.post('archives/wrsDoc/add', data).subscribe(res => {
        this.modalShow = false;
        this.fetchMenuList(true);
      });
    }
  }

  onCancel(): void {
    this.modalShow = false;
  }

  editNode(item, e): void {
    this.modalTitle = '修改节点';
    this.modalShow = true;
    this.folderForm.patchValue(item);
  }

  addNode(item, e): void {
    this.modalTitle = '新增节点';
    this.modalShow = true;
    this.folderForm.reset();
    this.folderForm.patchValue({pid: item.id});
  }

  deleteNode(item, e): void {
    this.fetchService.post<any>('archives/wrsDoc/delete', {id: item.id})
      .subscribe(res => {
        this.fetchMenuList(true);
      });
  }

  onFileDelete(id): void {
    this.fetchService.post<any>('archives/wrsDocFile/delete', {id: id})
      .subscribe(res => {
        this.getGridData();
      });
  }

  openFileUploadModal() {
    this.fileList = [];
    this.fileModalShow = true;
  }

  onFileCancel(): void {
    this.fileModalShow = false;
  }

  onFileConfirm(): void {
    const param = {
      docId: this.selectedItem.id,
      fileId: this.uploadFileId
    };
    this.fetchService.post<any>('archives/wrsDocFile/add', param).subscribe(res => {
      this.message.success('操作成功');
      this.fileModalShow = false;
      this.getGridData();
    });
  }

  handleChange({file, fileList}: UploadChangeParam): void {
    const status = file.status;
    this.uploadFileId = '';
    // 上传成功后
    if (status === 'done') {
      this.uploadFileId = file.response.data.id;
    }
  }

  // 查看
  checkDetail(e) {
    this.selectedItem = e.node ? e.node.origin : e;
    this.activedNode = e.node ? e.node : e;
    this.getGridData();

  }

  download(file): void {
    this.fetchService.export(`comm/file/down/${file.fileId}`, {
      responseType: 'blob'
    }).subscribe(data => {
      const fileBlob = new Blob([data], {type: 'charset=utf-8'});
      const link = document.createElement('a');
      link.id = 'materialsDownloadId';
      document.body.appendChild(link);
      link.style.display = 'none';
      link.download = file.fileName;
      link.href = URL.createObjectURL(fileBlob);
      link.click();
      const tempA = document.getElementById('materialsDownloadId');
      if (tempA) {
        tempA.parentNode.removeChild(tempA);
      }
    });
  }

  viewFile(file, tplContent: TemplateRef<{}>): void {
    const that = this;
    this.fileType = file.fileName.split('.')[1];
    this.fileId = file.fileId;
    this.fileSrc = `${(window as any).environment.apiBaseUrl}comm/file/view/${file.fileId}`;

    this.tplModal = this.modal.create({
      nzTitle: '文件预览',
      nzContent: tplContent,
      nzWidth: 1100,
      nzFooter: null,
      nzMaskClosable: false,
      nzClosable: true,
      nzOnCancel(): void {
        that.destroyModal();
      }
    });
  }

  destroyModal() {
    this.tplModal.destroy();
  }

}
